package com.moba.controller;

import com.alibaba.fastjson.JSONObject;
import com.moba.domain.SysSetting;
import com.moba.domain.UserInfo;
import com.moba.domain.UserMoneyApply;
import com.moba.domain.UserWallet;
import com.moba.emums.*;
import com.moba.service.UserMoneyApplyService;
import com.moba.service.UserWalletService;
import com.moba.utils.FieldFilter;
import com.moba.utils.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author li, bai, qiang
 * @version 2019-03-06 11:20
 * @date 2019-03-06 11:20
 */
@RestController
@RequestMapping("/userMoneyApply")
@Api(value = "")
public class UserMoneyApplyController extends BaseUserController {

  @Resource UserMoneyApplyService userMoneyApplyService;

  @Resource UserWalletService userWalletService;

  @ApiOperation(value = "获取列表")
  @GetMapping(value = "/list")
  public Object list(
      HttpServletRequest request,
      @ModelAttribute UserMoneyApply entity,
      String stDate,
      String enDate,
      String userNameLike,
      Integer page)
      throws Exception {

    if (null == page) {
      page = 1;
    }

    JSONObject jsonObject = new JSONObject();

    Map<String, Object> paramMap = WebUtils.getParametersStartingWith(request, FieldFilter.PREFIX);
    FieldFilter.setQuery(paramMap, entity);

    if (StringUtils.isNotBlank(userNameLike)) {
      UserInfo user = new UserInfo();
      user.setIsDel(0);
      user.getMap().put("user_name_like", userNameLike);
      user = userInfoService.getEntity(user);
      if (user != null) {
        entity.setUserId(user.getId());
      }
    }

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z"); // 格式化的表达式
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    if (StringUtils.isNotBlank(stDate)) {
      stDate = stDate.replace("Z", " UTC"); // 是空格+UTC
      Date d = format.parse(stDate);
      stDate = simpleDateFormat.format(d);
      entity.getMap().put("st_add_date", stDate);
    }

    if (StringUtils.isNotBlank(enDate)) {
      enDate = enDate.replace("Z", " UTC"); // 是空格+UTC
      Date d = format.parse(enDate);
      enDate = simpleDateFormat.format(d);
      entity.getMap().put("en_add_date", enDate);
    }

    entity.setIsDel(YesOrNo.YES_OR_NO_0.getIndex());
    jsonObject.put("dataCount", userMoneyApplyService.getEntityCount(entity));

    entity.getRow().setCount(10);
    entity.getRow().setFirst((page - 1) * (entity.getRow().getCount()));
    List<UserMoneyApply> entityList = userMoneyApplyService.getEntityPaginatedList(entity);
    jsonObject.put("entityList", entityList);

    UserMoneyApply userMoneyApply = new UserMoneyApply();
    userMoneyApply.setIsDel(YesOrNo.YES_OR_NO_0.getIndex());
    userMoneyApply.setInfoState(AuditState.AUDIT_STATE_1.getIndex());
    BigDecimal sumCashCount = userMoneyApplyService.getEntitySum(userMoneyApply);
    jsonObject.put("sumCashCount", sumCashCount);

    userMoneyApply.setInfoState(AuditState.AUDIT_STATE_0.getIndex());
    BigDecimal sumWaitCashCount = userMoneyApplyService.getEntitySum(userMoneyApply);
    jsonObject.put("sumWaitCashCount", sumWaitCashCount);

    UserInfo userInfo = new UserInfo();
    userInfo.setIsDel(0);
    userInfo.getMap().put("bi_usdt_ge", 0);
    BigDecimal sumUsdt = userInfoService.getEntitySumUsdt(userInfo);
    jsonObject.put("sumUsdt", sumUsdt);

    jsonObject.put(
        "auditStateList", super.parseEnmuToJSONArray(AuditState.class, AuditState.values()));
    //        jsonObject.put("applyType", super.parseEnmuToJSONArray(CashType.class,
    // CashType.values()));
    return ResultUtils.success(jsonObject);
  }

  @ApiOperation(value = "转账")
  @GetMapping(value = "/add")
  public Object add(@RequestParam(name = "userId") Integer userId) {

    if (null == super.getUserInfo(userId)) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "用户不存在！");
    }
    JSONObject jsonObject = new JSONObject();
    BigDecimal rate = new BigDecimal(super.getBaseDataById(601).getPreData());
    jsonObject.put("cashRate", rate);

    //        //查询钱包GHMI可用金额
    //        OrderInfo orderInfo=new OrderInfo();
    //        orderInfo.setAddUserId(userId);
    //        orderInfo.setOrderState(OrderState.ORDER_STATE_10.getIndex());
    //
    //        //调用钱包接口查询GHMI是否足够
    //        UserWallet userWallet=new UserWallet();
    //        userWallet.setUserId(userId);
    //        userWallet=userWalletService.getEntity(userWallet);
    //        if(userWallet==null){
    //            return ResultUtils.error(CodeType.CODE_TYPE_104,"用户钱包不存在！");
    //        }
    //        if(StringUtils.isBlank(userWallet.getEcr20Address())){
    //            return ResultUtils.error(CodeType.CODE_TYPE_104,"用户GHMI钱包地址错误！");
    //        }
    //        BigDecimal ghmi_total=new
    // BigDecimal(WalletHelp.getERC20Balance(userWallet.getEcr20Address()));
    //
    //        //查询冻结中也就是排单中的GHMI金额
    //        BigDecimal ghmi_used=orderInfoService.getEntitySumMoneyBi(orderInfo);
    //
    //        BigDecimal ghmi_has=ghmi_total.subtract(ghmi_used);
    //
    //        jsonObject.put("ghmi_total", ghmi_total);
    //        jsonObject.put("ghmi_used", ghmi_used);
    //        jsonObject.put("ghmi_has", ghmi_has);

    return ResultUtils.success(jsonObject);
  }

  @ApiOperation(value = "提币")
  @GetMapping(value = "/cashOut")
  public Object cashOut(@RequestParam(name = "userId") Integer userId) {

    if (null == super.getUserInfo(userId)) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "用户不存在！");
    }
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("cashRate", super.getMoneyApply(userId).get("rate"));
    jsonObject.put("cashCountBefore", super.getMoneyApply(userId).get("biUsdt"));
    return ResultUtils.success(jsonObject);
  }

  @ApiOperation(value = "提币审核")
  @PostMapping(value = "/audit")
  public Object audit(@RequestBody UserMoneyApply entity) {

    UserMoneyApply userMoneyApply = new UserMoneyApply();
    userMoneyApply.setId(entity.getId());
    userMoneyApply = userMoneyApplyService.getEntity(userMoneyApply);
    if (userMoneyApply == null) {
      return ResultUtils.error(CodeType.CODE_TYPE_102);
    }

    if (userMoneyApply.getInfoState().intValue() != AuditState.AUDIT_STATE_0.getIndex()) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "请勿重复审核！");
    }
    entity.setAuditDate(new Date());

    if (entity.getInfoState().intValue() == AuditState.AUDIT_STATE_X1.getIndex()) {
      // 审核不通过退还GHMI
      entity.getMap().put("returnBiUsdt", true);
    }
    int count = userMoneyApplyService.updateEntity(entity);
    if (count == 0) {
      return ResultUtils.error(CodeType.CODE_TYPE_102);
    }
    return ResultUtils.success();
  }

  /**
   * @author li, bai, qiang
   * @date 2019-03-07 9:47 转账页面点击转账传入UserMoneyApply对象调用此接口，来保存此条提现记录
   */
  @ApiOperation(value = "提币保存")
  @PostMapping(value = "/save")
  public Object save(@RequestBody UserMoneyApply entity) {

    logger.info("entity.getAddUid():" + entity.getAddUid());
    BigDecimal biUsdt = super.getMoneyApply(entity.getAddUid()).get("biUsdt");
    entity.setCashCountBefore(biUsdt);

    logger.info("biUsdt:" + biUsdt);

    if (biUsdt.compareTo(entity.getCashCount()) == -1) {
      return ResultUtils.error(CodeType.CODE_TYPE_101.getIndex(), "金额不足");
    }

    if (entity.getCashCount().compareTo(new BigDecimal(0)) == 0) {
      return ResultUtils.error(CodeType.CODE_TYPE_101.getIndex(), "金额不能为0");
    }

    if (null != entity.getId()) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }

    if (entity.getCashType() == null) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    // 提币手续费
    BigDecimal rate = rate = super.getMoneyApply(entity.getUserId()).get("rate");

    //        if(entity.getCashType().intValue()==CashType.CASH_TYPE_11.getIndex()){
    //            //提现
    //            rate = super.getMoneyApply(entity.getUserId()).get("rate");
    //        }

    BigDecimal cashRate =
        entity
            .getCashCount()
            .multiply(rate.divide(new BigDecimal(100)))
            .setScale(2, BigDecimal.ROUND_DOWN);

    entity.setCashRate(cashRate);
    entity.setCashPay(entity.getCashCount().subtract(cashRate));
    entity.setCashCountAfter(entity.getCashCountBefore().subtract(entity.getCashCount()));
    entity.setAddDate(new Date());
    entity.setInfoState(AuditState.AUDIT_STATE_0.getIndex());
    entity.getMap().put("biOutAndDoThing", true);
    entity.getMap().put("biType", BiType.BI_TYPE_300.getIndex());
    int count = userMoneyApplyService.createEntity(entity);
    if (count == 0) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    return ResultUtils.success();
  }

  @ApiOperation(value = "矿源充值")
  @PostMapping(value = "/saveUserOrderMoneySum")
  public Object saveUserOrderMoneySum(@RequestBody UserMoneyApply entity) {

    UserInfo userInfo = super.getUserInfo(entity.getAddUid());
    if (null == userInfo) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "用户不存在");
    }

    if (entity.getCashType() == null) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    if (entity.getCashCount() == null) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }

    if (entity.getCashCount().compareTo(new BigDecimal(0)) == 0) {
      return ResultUtils.error(CodeType.CODE_TYPE_101.getIndex(), "金额不能为0");
    }

    if (entity.getOptType().intValue() == BiType.BI_TYPE_100.getIndex()) {
      if (userInfo.getBiDianzi().compareTo(entity.getCashCount()) == -1) {
        return ResultUtils.error(CodeType.CODE_TYPE_101.getIndex(), "金额不足");
      }
    } else if (entity.getOptType().intValue() == BiType.BI_TYPE_500.getIndex()) {
      if (userInfo.getGusd().compareTo(entity.getCashCount()) == -1) {
        return ResultUtils.error(CodeType.CODE_TYPE_101.getIndex(), "金额不足");
      }
    } else {
      return ResultUtils.error(CodeType.CODE_TYPE_101.getIndex(), "充值类型不正确");
    }

    // 查询汇率
    BigDecimal rate = new BigDecimal(2);
    try {
      //        rate = WalletHelp.getExchangeRate("GHMI");
      //        logger.info("=====rate:" + rate);
    } catch (Exception e) {

    }
    // TODO
    rate = new BigDecimal(2);

    entity.getMap().put("sub_bi_count", entity.getCashCount());

    SysSetting sys = super.getSysSetting(SysSettingType.orderMoneySumRate.getIndex());
    BigDecimal orderMoneySumRate = new BigDecimal(sys.getContent());
    BigDecimal cashCount = entity.getCashCount().divide(rate).multiply(orderMoneySumRate);
    entity.setCashCount(cashCount);

    entity.setCashRate(new BigDecimal(0));
    entity.setCashPay(entity.getCashCount());
    entity.setCashCountBefore(userInfo.getOrderMoneySum());
    entity.setCashCountAfter(entity.getCashCountBefore().subtract(entity.getCashCount()));
    entity.setAddDate(new Date());
    entity.setInfoState(AuditState.AUDIT_STATE_0.getIndex());
    entity.getMap().put("saveUserOrderMoneySum", true);
    int count = userMoneyApplyService.createEntity(entity);
    if (count == 0) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }
    return ResultUtils.success();
  }

  @ApiOperation(value = "查询单条记录")
  @GetMapping(value = "/{id}")
  public Object edit(@PathVariable(name = "id") Integer id) {

    UserMoneyApply entity = new UserMoneyApply();
    entity.setId(id);
    entity = userMoneyApplyService.getEntity(entity);
    if (null == entity) {
      return ResultUtils.error(CodeType.CODE_TYPE_102);
    }
    entity
        .getMap()
        .put("auditStateList", super.parseEnmuToJSONArray(AuditState.class, AuditState.values()));

    // 查询当前用户已提金额
    UserMoneyApply userMoneyApply = new UserMoneyApply();
    userMoneyApply.setIsDel(YesOrNo.YES_OR_NO_0.getIndex());
    userMoneyApply.setInfoState(AuditState.AUDIT_STATE_1.getIndex());
    userMoneyApply.setAddUid(entity.getAddUid());
    BigDecimal sumCashCount = userMoneyApplyService.getEntitySum(userMoneyApply);
    entity.getMap().put("sumCashCount", sumCashCount);

    userMoneyApply.setInfoState(AuditState.AUDIT_STATE_0.getIndex());
    BigDecimal sumWaitCashCount = userMoneyApplyService.getEntitySum(userMoneyApply);
    entity.getMap().put("sumWaitCashCount", sumWaitCashCount);

    UserInfo userInfo = new UserInfo();
    userInfo.setIsDel(0);
    userInfo.setId(entity.getAddUid());
    userInfo = userInfoService.getEntity(userInfo);
    if (null == userInfo) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "用户不存在！");
    }
    entity.getMap().put("biUsdt", userInfo.getBiUsdt());

    UserWallet wallet = new UserWallet();
    wallet.setUserId(entity.getAddUid());
    wallet = userWalletService.getEntity(wallet);
    if (wallet != null) {
      entity.getMap().put("usdtAddr", wallet.getUsdtAddress());
    }

    return ResultUtils.success(entity);
  }
}
